<template>
  <section>
    <el-dialog
      title="设置权限"
      :visible.sync="visible"
      :value="value" 
      width="600px"
    >
      <el-transfer
        v-model="powerInfo.selectedIds"
        :data="permissions"
        :titles="['待选权限','已选权限']"
        filterable
        filter-placeholder="请输入权限名称"
        :props="{
          key: 'id',
          label: 'description'
        }"
      />
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          size="small"
          @click="cancle"
        >取 消</el-button>
        <el-button
          size="small"
          type="primary"
          @click="submit"
        >确 定</el-button>
      </span>
    </el-dialog>
  </section>
</template>
<style>
</style>
<script>
export default {
  name: "RolePermission",
  data() {
    return {
      visible: false,
      labelWidth: "",
      permissions: [],
      applications: [],
      powerInfo: {
        selectedIds: [],
        id: 0
      }
    };
  },
  watch: {
    value: {
      deep: true,
      immediate: true,
      handler: function(val) {
        this.visible = val.show;
        this.labelWidth = val.formLabelWidth;
        this.powerInfo.id = val.id;
        this.applications = val.applications;
        this.$api.role.getRolePermissions(val.id, result => {
          this.permissions = result.infos;
          this.powerInfo.selectedIds = this.permissions
            .filter(item => item.selected)
            .map(item => item.id);
        });
      }
    },
    visible(val) {
      if (!val) this.$emit("on-show-change", this.$data);
    }
  },
  methods: {
    cancle() {
      this.visible = false;
      this.powerInfo = {
        selectedIds: [],
        id: 0
      };
    },
    submit() {
      this.$api.role.grantPermission(this.powerInfo, () => {
        this.$message({
          type: "success",
          message: "授权成功",
          onClose: this.cancle
        });
      });
    }
  },
  props: {
    value: {
      type: Object,
      default: function() {
        return {
          show: false,
          formLabelWidth: "120px",
          id: 0,
          applications: []
        };
      }
    }
  }
};
</script>
